package com.example.leixin.helloworld.weather;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.leixin.helloworld.R;
import com.example.leixin.helloworld.net.HttpUtil;
import com.example.leixin.helloworld.weather.gson.Forecast;
import com.example.leixin.helloworld.weather.gson.Weather;
import com.example.leixin.helloworld.weather.service.AutoUpdateService;
import com.example.leixin.helloworld.weather.util.Utility;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherDetailAcitvity extends AppCompatActivity {

    private ScrollView weatherScrollView;
    private TextView cityTextView;
    private TextView updateTimeTextView;
    private TextView degreeTextView;
    private TextView weatherInfoTextView;
    private LinearLayout forecastLayout;
    private TextView apiTextView;
    private TextView pm25TextView;
    private TextView comfortTextView;
    private TextView carWashTextView;
    private TextView sportTextView;
    private ImageView bingPicImageView;
    public SwipeRefreshLayout swipeRefreshLayout;
    public DrawerLayout drawerLayout;
    private Button navButton;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weather_detail);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        weatherScrollView = (ScrollView) findViewById(R.id.weather_layout);
        cityTextView = (TextView) findViewById(R.id.title_city);
        updateTimeTextView = (TextView) findViewById(R.id.title_update_time);
        degreeTextView = (TextView) findViewById(R.id.degree_text);
        weatherInfoTextView = (TextView) findViewById(R.id.weather_info_text);
        forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
        apiTextView = (TextView) findViewById(R.id.aqi_text);
        pm25TextView = (TextView) findViewById(R.id.pm25_text);
        comfortTextView = (TextView) findViewById(R.id.comfort_text);
        carWashTextView = (TextView) findViewById(R.id.car_wash_text);
        sportTextView = (TextView) findViewById(R.id.sport_text);
        bingPicImageView = (ImageView) findViewById(R.id.bing_pic_img);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navButton = (Button) findViewById(R.id.nav_button);

        final String weatherId;

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString = sharedPreferences.getString("weather", null);
        if (weatherString != null) {
            Weather weather = Utility.handleWeatherResponse(weatherString);
            weatherId = weather.basic.weatherId;
            showWeatherInfo(weather);
        } else {
            weatherId = getIntent().getStringExtra("weather_id");
            weatherScrollView.setVisibility(View.INVISIBLE);
            requestWeather(weatherId);
        }

        String bingPic = sharedPreferences.getString("bing_pic", null);
        if (bingPic != null) {
            Glide.with(this).load(bingPic).into(bingPicImageView);
        } else {
            loadBingPic();
        }

        swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestWeather(weatherId);
            }
        });

        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(Gravity.START);
            }
        });

        Intent intent = new Intent(this, AutoUpdateService.class);
        startService(intent);
    }

    private void loadBingPic() {
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherDetailAcitvity.this).edit();
                editor.putString("bing_pic", bingPic);
                editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(WeatherDetailAcitvity.this).load(bingPic).into(bingPicImageView);
                    }
                });
            }
        });
    }

    public void requestWeather(final String weatherId) {
        String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=c91365ce8a0042b391dd740047ae4972";
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherDetailAcitvity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                final Weather weather = Utility.handleWeatherResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (weather != null && "ok".equals(weather.status)) {
                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherDetailAcitvity.this).edit();
                            editor.putString("weather", responseText);
                            editor.apply();
                            showWeatherInfo(weather);
                        } else {
                            Toast.makeText(WeatherDetailAcitvity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        }

                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }
        });

        loadBingPic();
    }

    private void showWeatherInfo(Weather weather) {
        String cityName = weather.basic.cityName;
        String updateTime = weather.basic.update.updateTime.split(" ")[1];
        String degree = weather.now.temperature + "度";
        String weatherInfo = weather.now.more.info;
        cityTextView.setText(cityName);
        updateTimeTextView.setText(updateTime);
        degreeTextView.setText(degree);
        weatherInfoTextView.setText(weatherInfo);
        forecastLayout.removeAllViews();

        for (Forecast forecast : weather.forecastList) {
            View view = LayoutInflater.from(this).inflate(R.layout.weather_forecast_item, forecastLayout, false);
            TextView dateTextView = (TextView) view.findViewById(R.id.date_text);
            TextView infoTextView = (TextView) view.findViewById(R.id.info_text);
            TextView maxTextView = (TextView) view.findViewById(R.id.max_text);
            TextView minTextView = (TextView) view.findViewById(R.id.min_text);

            dateTextView.setText(forecast.date);
            infoTextView.setText(forecast.more.info);
            maxTextView.setText(forecast.temperature.max);
            minTextView.setText(forecast.temperature.min);
            forecastLayout.addView(view);
        }

        if (weather.aqi != null) {
            apiTextView.setText(weather.aqi.city.aqi);
            pm25TextView.setText(weather.aqi.city.pm25);
        }

        String comfort = weather.suggestion.comfort.info;
        String carWash = weather.suggestion.carWash.info;
        String sport = weather.suggestion.sport.info;
        comfortTextView.setText(comfort);
        carWashTextView.setText(carWash);
        sportTextView.setText(sport);
        weatherScrollView.setVisibility(View.VISIBLE);
    }
}
